/*
 * @Author: Cao Shixin
 * @Date: 2021-01-29 16:25:15
 * @LastEditors: Cao Shixin
 * @LastEditTime: 2021-05-26 18:00:38
 * @Description: 自定义设置log的一些规则：过滤、打印、输出
 */

import 'package:logger_csx/logger_csx.dart';
import 'log_model.dart';

/* 有日期有等级的输出
 * 
 * 样式：[2021-01-19T14:22:32.149445 level=debug][文件名 tag]:message
 */
class LogDatePrinter extends LogPrinter {
  static final levelPrefixes = {
    Level.verbose: 'verbose',
    Level.debug: 'debug',
    Level.info: 'info',
    Level.warning: 'warning',
    Level.error: 'error',
    Level.wtf: 'wtf',
  };

  @override
  List<String> log(LogEvent event) {
    LogExtraParam logExtraParam = LogExtraParam.fromJson(event.extraParam);
    var sub = '[';
    if (logExtraParam.fileSubName != 'base') {
      sub += '${logExtraParam.fileSubName} ';
    }
    sub += '${logExtraParam.tag}]';
    var output = StringBuffer(
        '[${DateTime.now().toIso8601String()} level=${levelPrefixes[event.level]}]$sub: ');
    if (event.message is String) {
      output.write('${event.message}');
    } else if (event.message is Map) {
      event.message.entries.forEach((entry) {
        if (entry.value is num) {
          output.write(' ${entry.key}=${entry.value}');
        } else {
          output.write(' ${entry.key}="${entry.value}"');
        }
      });
    }
    return [output.toString()];
  }
}

class ConsoleLogOutput extends LogOutput {
  //长度打印，限制最大长度300
  final int maxLength = 300;
  @override
  void output(OutputEvent event) {
    event.lines.forEach((cell) {
      while (cell.length > maxLength) {
        print('${cell.substring(0, maxLength)}');
        cell = cell.substring(maxLength, cell.length);
      }
      print(cell);
    });
  }
}
